package com.my.code.threadpool;

import java.util.LinkedList;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 简易线程池的实现
 *
 * @author zzl
 * @date 2020/10/14
 */
public class MyThreadPool implements ThreadPool<Runnable> {

    private static final int MAX_THREAD_NUM = 128;
    private static final int MAX_TASK_NUM = 1024;

    private final ArrayBlockingQueue<Runnable> queue;
    private final LinkedList<WorkThread> workers;

    public MyThreadPool(int size) {
        if (size > MAX_THREAD_NUM) size = MAX_THREAD_NUM;
        queue = new ArrayBlockingQueue<>(MAX_TASK_NUM);
        workers = new LinkedList<>();
        for (int i = 0; i < size; i++) {
            WorkThread workThread = new WorkThread(queue);
            workers.add(workThread);
            workThread.start();
        }
    }

    @Override
    public void execute(Runnable task) {
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void shutdown() {
        synchronized (this) {
            for (WorkThread workThread : workers) {
                workThread.cancel();
            }
        }
        queue.clear();
    }

    @Override
    public void addWorker(int num) {

    }

    @Override
    public void removeWorker(int num) {

    }

    @Override
    public int getTaskSize() {
        return queue.size();
    }

}
